package com.doroodo.sys.action;

import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import com.doroodo.base.action.BaseAction;
import com.doroodo.base.fixflow.FixFlowMag;
import com.doroodo.base.model.DataGrid;
import com.doroodo.sys.model.SyModule;
import com.doroodo.sys.service.SyModuleService;
import com.founder.fix.fixflow.core.ProcessEngine;
import com.founder.fix.fixflow.core.runtime.ProcessInstance;
import com.founder.fix.fixflow.util.Pagination;
import com.founder.fix.fixflow.core.impl.runtime.*;

/** 
* @ClassName: SyFlowAction 
* @Description:  
* @author:sky
* @date 2013-9-22 下午03:37:33 
*  
*/ 
@Controller
@ParentPackage(value="sys")   
@InterceptorRef("mydefault")  
public class SyFlowAction extends BaseAction {
	@Autowired
	private SyModuleService syModuleService;
	@Autowired
	private FixFlowMag fixFlowMag;
	
	private static final long serialVersionUID = 1L;
	
	private String taskPsK="";//流程业务参数名
	private String taskPsV="";//流程业务参数值

	public String getTaskPsK() {
		return taskPsK;
	}

	public void setTaskPsK(String taskPsK) {
		this.taskPsK = taskPsK;
	}

	public String getTaskPsV() {
		return taskPsV;
	}

	public void setTaskPsV(String taskPsV) {
		this.taskPsV = taskPsV;
	}

	@Action("/sys/syFlow_GET_ArchivingFlow")
	public void syFlowGetArchivingFlow(){
		Map<String, Object> filter = new HashMap<String, Object>();
		filter.put("userId", getLoginUserId());
		int page=this.getPage();
		if(page==0)page=1;
		filter.put("pageIndex",page );
		int rows=this.getRows();
		if(rows==0)rows=20;
		filter.put("pageSize",rows);
		DataGrid dg = new DataGrid();
		try {
			Map<String,Object> map=this.getFlowCenter().queryMyTaskEnded(filter);
			dg.setRows((List)map.get("dataList"));
			Pagination p=(Pagination)map.get("pageInfo");
			dg.setTotal((long)p.getTotal());
		} catch (SQLException e) {
			e.printStackTrace();
		}
		this.writeJson(dg);
	}
	
	@Action("/sys/syFlow_List")
	public void syFlowList(){
		Map<String, Object> filter = new HashMap<String, Object>();
		Map<String, Object> result = null;
		filter.put("userId", getLoginUserId());
		int page=this.getPage();
		if(page==0)page=1;
		filter.put("pageIndex",page );
		int rows=this.getRows();
		if(rows==0)rows=20;
		filter.put("pageSize",rows);
		DataGrid dg = new DataGrid();
		try {
			result = this.getProcessDefinitionService().getProcessDefitionList(filter);
			Pagination p=(Pagination)result.get("pageInfo");
			dg.setTotal((long)p.getTotal());
			List<Map<String,Object>> processDefinitionList=(List)result.get("dataList");
			for(int i=0;i<processDefinitionList.size();i++){
				Map<String,Object> map=processDefinitionList.get(i);
				map.put("id", map.get("deploymentId"));
				processDefinitionList.set(i, map);
			}
			dg.setRows(processDefinitionList);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		this.writeJson(dg);
	}
	
	@Action("/sys/syFlow_List_ByUserID")
	public void syFlowListByUserID(){
		
		List<Map<String, String>> result = null;
		ProcessEngine processEngine=fixFlowMag.getProcessEngine();
		processEngine.cleanCache(true,true);
		try{
			result=processEngine.getModelService().getStartProcessByUserId(this.getLoginUserId());
		}catch(Exception ex){
			ex.printStackTrace();
		}
		
		this.writeJson(result);
	}
	
	
	@Action("/sys/syFlow_Get_Toobar")
	public void syFlowGetToobar(){
		String taskId=this.getTaskId();
		String processDefinitionKey=this.getProcessDefinitionKey();
		if("".equalsIgnoreCase(processDefinitionKey)) return ;
		Map<String, Object> filter = new HashMap<String, Object>();
		filter.put("userId", getLoginUserId());
		filter.put("taskId", taskId);
		filter.put("processDefinitionKey",processDefinitionKey);
		this.writeJson(this.getFlowToolBarBytaskId(filter));
	}
	
	@Action("/sys/syFlow_Get_TaskDetailInfo")
	public void syFlowGetTaskDetailInfo(){
		String taskId=this.getTaskId();
		String processInstanceId=this.getProcessInstanceId();
		if("".equalsIgnoreCase(processInstanceId)) return ;
		Map<String, Object> filter = new HashMap<String, Object>();
		filter.put("userId", getLoginUserId());
		filter.put("taskId", taskId);
		filter.put("processInstanceId",processInstanceId);
		this.writeJson(this.getTaskDetailInfo(filter));
	}
	
	@Action("/sys/syFlow_Get_TaskDetailInfoList")
	public void syFlowGetTaskDetailInfoList(){
		String taskId=this.getTaskId();
		String processInstanceId=this.getProcessInstanceId();
		if("".equalsIgnoreCase(processInstanceId)) return ;
		Map<String, Object> filter = new HashMap<String, Object>();
		filter.put("userId", getLoginUserId());
		filter.put("taskId", taskId);
		filter.put("processInstanceId",processInstanceId);
		List<Map<String,Object>> list=(List<Map<String, Object>>) this.getTaskDetailInfo(filter).get("dataList");
		List<Map<String,Object>> list_=(List<Map<String, Object>>) this.getTaskDetailInfo(filter).get("notEnddataList");
		list.addAll(list_);
		this.writeJson(list);
	}
	
	@Action("/sys/syFlow_Do_Task")
	public void syFlowDoTask(){
		Map<String, Object> filter = new HashMap<String, Object>();
		String psV=this.getTaskPsV();
		String psK=this.getTaskPsK();
		if( (!psK.isEmpty()) && (!psV.isEmpty()) ){
			String[] psKs=psK.split(",");
			String[] psVs=psV.split("\\^");
			if(psKs.length<=psVs.length){
				filter.put("psV", psVs);
				filter.put("psK", psKs);
			}
		}
		filter.put("userId", getLoginUserId());
		filter.put("taskId", this.getTaskId());
		filter.put("commandType", this.getCommandType());
		filter.put("commandId", this.getCommandId());
		filter.put("processDefinitionKey", this.getProcessDefinitionKey());
		filter.put("businessKey", this.getBusinessKey());
		filter.put("taskComment", this.getTaskComment());
		filter.put("taskParams", this.getTaskParams());
		try {
			this.getFlowCenter().completeTask(filter);
			this.writeMsg(this.DOWORKFOW_SUC);
		} catch (SQLException e) {
			this.writeMsg(DOWORKFOW_ER);
			e.printStackTrace();
		}
	}
	
	
	@Action("/sys/syFlow_Get_ToDoListByUserID")
	public void syFlowToDoListByUserID(){
		List<Map<String, String>> result = null;
		Map<String, Object> filter = new HashMap<String, Object>();
		filter.put("userId", getLoginUserId());
		int page=this.getPage();
		if(page==0)page=1;
		filter.put("pageIndex",page );
		int rows=this.getRows();
		if(rows==0)rows=20;
		filter.put("pageSize",rows);
		DataGrid dg = new DataGrid();
		try {
			Map<String,Object> map=this.getFlowCenter().queryMyTaskNotEnd(filter);
			this.writeJson(map.get("dataList"));
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	
	//获取流程toolbar
	@Action("/sys/syFlow_Get_FlowToolBarBytaskId")
	public void syFlowGetFlowToolBarBytaskId(){
		String taskId=this.getTaskId();
		String processDefinitionKey=this.getProcessDefinitionKey();
		if("".equalsIgnoreCase(processDefinitionKey)) return;
		Map<String, Object> filter = new HashMap<String, Object>();
		Map<String, Object> result = null;
		filter.put("userId", getLoginUserId());
		filter.put("taskId", taskId);
		filter.put("processDefinitionKey",processDefinitionKey);
		try {
			result=this.getFlowCenter().GetFlowRefInfo(filter);
			Map<String,Object> map=new HashMap();
			map.put("commandList", result.get("commandList"));
			this.writeJson(map);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	//获取流程图片
	@Action("/sys/syFlow_Get_FlowImageByDefId")
	public void syFlowGetFlowImageByDefId(){
		if(this.getProcessDefinitionId()=="")return;
		InputStream ps= this.getFlowImageByDefId(this.getProcessDefinitionId());
		try {
			getResponse().setContentType("image/*"); 
			getResponse().getOutputStream().write(this.SUNTIL.toByteArray(ps));
			getResponse().getOutputStream().close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	//获取流程图片
		@Action("/sys/syFlow_Get_FlowImage")
		public void syFlowGetFlowImage(){
			if(this.getProcessDefinitionId()==""&& this.getProcessDefinitionKey()=="")return;
			Map<String, Object> filter = new HashMap<String, Object>();
			filter.put("processDefinitionKey",this.getProcessDefinitionKey());
			filter.put("processDefinitionId",this.getProcessDefinitionId());
			InputStream ps = null;
			try {
				ps = this.getFlowCenter().getFlowGraph(filter);
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
			try {
				getResponse().setContentType("image/*"); 
				getResponse().getOutputStream().write(this.SUNTIL.toByteArray(ps));
				getResponse().getOutputStream().close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	//启动流程
	@Action("/sys/syFlow_Start_ProcByKey")
	public void syFlowStartProcByKey(){
		if(this.getProcessDefinitionKey()=="")return;
		ProcessInstance processInstance=this.startOneProc(this.getProcessDefinitionKey(), 
				"bk_StartProcessInstanceTest", this.getLoginUserId());
		if(processInstance==null){
			this.writeMsg(STARTWORKFOW_ER);
		}else{
			Map<String,Object> map=new HashMap();
			map.put("info", STARTWORKFOW_SUC);
			String taskInstanceId=((ProcessInstanceEntity)processInstance).
					getTaskMgmtInstance().getTaskInstanceEntitys().get(1).getId();
			map.put("processInstanceId",processInstance.getId());
			map.put("taskInstanceId",taskInstanceId);
			this.writeJson(map);
		}
	}
	
	private String getModuleUrl(String strModule){
		SyModule module=new SyModule();
		module.setMenuname(strModule);
		module.setState("");
		List<SyModule> modules =syModuleService.get(module);
		if(modules.size()==1){
			return modules.get(0).getUrl();
		}else{
			return null;
		}
	}
	
	
	//流程上传
	@Action("/sys/syFlow_Upload")
	public void syFlowUpload() throws IOException{
		Map<String, Object> filter = new HashMap<String, Object>();
		String msg=FIle_UPLOAD_SUC;
		try {
			filter.put("userId", getLoginUserId());
			filter.put("ProcessFile",this.SUNTIL.fileToFileItem(this.getUploadFile()));
			getProcessDefinitionService().deployByZip(filter);
		} catch (Exception e) {
			e.printStackTrace();
			msg=FIle_UPLOAD_ER;
		}finally{
			this.writeMsg(msg);
		}
	}

	@Action("/sys/syFlow_Delete")
	public void syFlowDelete(){
		Map<String, Object> filter = new HashMap<String, Object>();
		filter.put("userId", getLoginUserId());
		filter.put("deploymentId", this.getIds());
		getProcessDefinitionService().deleteDeploy(filter);
		this.writeMsg(DEL_SUC);
	}
	
	@Action("/sys/syFlow_Update")
	public void syFlowUpdate(){
		//if(syFlow!=null) syFlowService.saveOrUpdate(syFlow);
		writeMsg(this.EDIT_SUC);
	}
	
}
